package com.hula.onion.book.server.spider.platforms.lianjinsuo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by work on 2018/1/25.
 */
@Component
public class LianJinSuoSpiderHelper {
    public Map<String, Object> installRequestParams(LoginForm loginForm) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("paramMap.pageId", "userlogin");
        map.put("paramMap.email", loginForm.getUserName());
        map.put("paramMap.password", loginForm.getPassword());
        map.put("paramMap.autoLogin", "N");
        map.put("paramMap.afterLoginUrl", "");
        map.put("paramMap.goDuangPage", "");
        map.put("paramMap.backToLjmdIndexPage", "");
        return map;
    }


    /**
     * 解析账户余额
     *
     * @param accountDetailJson
     * @param accountHtml
     * @return
     */
    public CommonResponse parseAccountBalance(String accountDetailJson, String accountHtml) {
        if (StringUtils.isEmpty(accountDetailJson)
                && StringUtils.isEmpty(accountHtml)) {
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }
        AccountInfo accountInfo = new AccountInfo();
        if (StringUtils.isNotEmpty(accountDetailJson)) {
            JSONObject jsonObject = JSON.parseObject(accountDetailJson);
            BigDecimal cash = jsonObject.getBigDecimal("cash");
            BigDecimal toCollectInterest = jsonObject.getBigDecimal("toCollectInterest");
            BigDecimal toCollectPrincipal = jsonObject.getBigDecimal("toCollectPrincipal");
            BigDecimal ljmdFreezeSum = jsonObject.getBigDecimal("ljmdFreezeSum");
            BigDecimal frozenWithDrawCash = jsonObject.getBigDecimal("frozenWithDrawCash");
            BigDecimal frozenBiddingCash = jsonObject.getBigDecimal("frozenBiddingCash");
            BigDecimal amount = cash.add(toCollectInterest).add(toCollectPrincipal)
                    .add(ljmdFreezeSum).add(frozenBiddingCash).add(frozenWithDrawCash);
            accountInfo.setAmount(amount);
        }
        if (StringUtils.isNotEmpty(accountHtml)) {
            Document document = Jsoup.parse(accountHtml);
            Element el = document.selectFirst("div.zl_r");
            String totalIntrest = el.getAllElements().get(9).text();
            accountInfo.setTotalIntrest(new BigDecimal(totalIntrest));
        }
        return new CommonResponse(accountInfo);
    }
}
